package com.molyfun.parents.fragment.dialog;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.attachment.AttachmentView;
import com.molyfun.parents.dao.entity.CourseFeedBackDB;
import com.molyfun.parents.dao.gen.CourseFeedBackDBDao;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.impl.IPicUploadCallback;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.AddCourseFeedBackRequest;
import com.molyfun.parents.rest.bean.CourseFeedbackEditRequest;
import com.molyfun.parents.rest.bean.CourseFeedbackListResponse;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.UIUtils;
import com.molyfun.parents.view.common.MfEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CourseFeedbackDialogFragment extends DialogFragment implements View.OnClickListener, IPicUploadCallback, AttachmentView.AttachmentAddCallback {

    @InjectView(R.id.course_feedback_text)
    MfEditText mFeedbackEdt;
    @InjectView(R.id.course_feedback_attachview)
    AttachmentView mAttachmentView;
    @InjectView(R.id.commit)
    TextView mCommit;
    @InjectView(R.id.title)
    TextView mTitle;

    private String mCourseId, mCourseDownloadKey;
    private CourseFeedBackDBDao courseFeedBackDBDao;
    private CourseFeedbackListResponse.CourseFeedbackBean courseFeedbackBean;


    private static CourseFeedbackDialogFragment newInstance(String courseId, String courseDownloadKey, CourseFeedbackListResponse.CourseFeedbackBean courseFeedbackBean) {
        CourseFeedbackDialogFragment mStudentMenuDialogFragment = new CourseFeedbackDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Const.COURSE_ID, courseId);
        bundle.putString(Const.COURSE_DOWNLOAD_ID, courseDownloadKey);
        bundle.putParcelable(Const.COURSE_FEEDBACK_BEAN, courseFeedbackBean);
        mStudentMenuDialogFragment.setArguments(bundle);
        return mStudentMenuDialogFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setCancelable(false);
//        setStyle(DialogFragment.STYLE_NORMAL, R.style.BaseDialog);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.dialog_course_feedback, container, false);
        ButterKnife.inject(this, view);

        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        courseFeedBackDBDao = daoSession.getCourseFeedBackDBDao();
        mCourseId = (String) getArguments().get(Const.COURSE_ID);
        courseFeedbackBean = getArguments().getParcelable(Const.COURSE_FEEDBACK_BEAN);
        mCourseDownloadKey = (String) getArguments().get(Const.COURSE_DOWNLOAD_ID);

        CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
        if (courseFeedBackDB != null) {
            mFeedbackEdt.setText(courseFeedBackDB.getFeedback());
        }
        if (courseFeedbackBean != null) {
            mFeedbackEdt.setText(courseFeedbackBean.getContent());
            mAttachmentView.addList(courseFeedbackBean.getMediaobjectlist());
            mTitle.setText("修改反馈");
        }

        view.findViewById(R.id.close).setOnClickListener(this);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText("课程反馈");
        mCommit.setOnClickListener(this);
        mAttachmentView.setAttachmentAddCallback(this);
//        DayCourseListActivity.setIPicUploadCallback(this);
        return view;
    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(originalUrl);
        mediaAttachment.setType(1);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {
    }

    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        System.out.println("cover--->" + cover);
        System.out.println("path--->" + path);

        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(path);
        mediaAttachment.setType(2);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    @Override
    public void onAttachmentAdd() {
        if (getActivity() instanceof BaseChoosePicActivity) {
            ((BaseChoosePicActivity) getActivity()).chooseMedia();
        }

    }

    @Override
    public String getAttachmentFolder() {
        return "coursefb";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                if (!TextUtils.isEmpty(mFeedbackEdt.getText().toString().trim())) {
                    CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
                    if (courseFeedBackDB != null) {
                        courseFeedBackDB.setFeedback(mFeedbackEdt.getText().toString().trim());
                        courseFeedBackDBDao.update(courseFeedBackDB);
                    } else {
                        CourseFeedBackDB newCourseFeedBackDB = new CourseFeedBackDB();
                        newCourseFeedBackDB.setFeedback(mFeedbackEdt.getText().toString().trim());
                        newCourseFeedBackDB.setDownloadKeyId(mCourseDownloadKey);
                        courseFeedBackDBDao.insert(newCourseFeedBackDB);
                    }
                }
//                DayCourseListActivity.removeIPicUploadCallback(this);
                getDialog().dismiss();
                break;
            case R.id.commit:
                if (TextUtils.isEmpty(mFeedbackEdt.getText().toString().trim())) {
                    UIUtils.showToast(getContext(), "请输入反馈内容");
                    return;
                }
                mCommit.setClickable(false);
                sendFeedBack();
                break;
            default:
//                DayCourseListActivity.removeIPicUploadCallback(this);
                getDialog().dismiss();
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    private void sendFeedBack() {
        if (courseFeedbackBean != null) {
            final CourseFeedbackEditRequest courseFeedbackEditRequest = new CourseFeedbackEditRequest();
            courseFeedbackEditRequest.setContent(mFeedbackEdt.getText().toString().trim());
            courseFeedbackEditRequest.setId(courseFeedbackBean.getId());
            courseFeedbackEditRequest.setMediaobjectlist(mAttachmentView.getAttachment());
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().updateCourseFeedback(courseFeedbackEditRequest);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {
                        if (mCourseFeedbackCallback != null) {
                            mCourseFeedbackCallback.onFeedbackUpdateSuccess(courseFeedbackEditRequest);
                        }
                        //TODO 删除数据库操作
                       /* CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
                        if (courseFeedBackDB != null) {
                            courseFeedBackDBDao.delete(courseFeedBackDB);
                        }*/

                        UIUtils.showToast(getContext(), "提交成功");
                        getDialog().dismiss();


                    } else {
                        UIUtils.showToast(getContext(), response.body().getMsg());
                        mCommit.setClickable(true);
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    mCommit.setClickable(true);
                }
            });
        } else {
            AddCourseFeedBackRequest addCourseFeedBackRequest = new AddCourseFeedBackRequest();
            addCourseFeedBackRequest.setContent(mFeedbackEdt.getText().toString().trim());
            addCourseFeedBackRequest.setCoursesummaryid(mCourseId);
            addCourseFeedBackRequest.setMediaobjectlist(mAttachmentView.getAttachment());


            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().addCourseFeedBack(addCourseFeedBackRequest);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {
                        if (mCourseFeedbackCallback != null) {
                            mCourseFeedbackCallback.onFeedbackSuccess();
//                            Message message = new Message();
//                            message.what = EventDispatcherEnum.UI_EVENT_REPORTFROMSCOURSE_FREEBACK;
//                            MFPApplication.getInstance().getEventDispatcher().sendMessage(message);
                        }

                        CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
                        if (courseFeedBackDB != null) {
                            courseFeedBackDBDao.delete(courseFeedBackDB);
                        }

                        UIUtils.showToast(getContext(), "提交成功");
                        getDialog().dismiss();

                    } else {
                        UIUtils.showToast(getContext(), response.body().getMsg());
                        mCommit.setClickable(true);
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    mCommit.setClickable(true);
                }
            });
        }


    }

    public interface CourseFeedbackCallback {
        void onFeedbackSuccess();

        void onFeedbackUpdateSuccess(CourseFeedbackEditRequest courseFeedbackEditRequest);
    }

    private CourseFeedbackCallback mCourseFeedbackCallback;

    public void setCourseFeedbackCallback(CourseFeedbackCallback courseFeedbackCallback) {
        this.mCourseFeedbackCallback = courseFeedbackCallback;
    }

    public static class CourseFeedbackDialogBuilder {

        CourseFeedbackDialogFragment mCourseFeedbackDialogFragment;
        private String mTag;

        public CourseFeedbackDialogBuilder(String courseId, String downloadId) {
            mCourseFeedbackDialogFragment = CourseFeedbackDialogFragment.newInstance(courseId, downloadId, null);
            mTag = "course_feedback";
        }

        public CourseFeedbackDialogBuilder(String courseId, String downloadId, CourseFeedbackListResponse.CourseFeedbackBean courseFeedbackBean) {
            mCourseFeedbackDialogFragment = CourseFeedbackDialogFragment.newInstance(courseId, downloadId, courseFeedbackBean);
            mTag = "course_feedback";
        }

        public CourseFeedbackDialogBuilder setCourseFeedbackCallback(CourseFeedbackCallback courseFeedbackCallback) {
            this.mCourseFeedbackDialogFragment.setCourseFeedbackCallback(courseFeedbackCallback);
            return this;
        }

        public CourseFeedbackDialogBuilder setTag(String tag) {
            this.mTag = tag;
            return this;
        }

        public CourseFeedbackDialogFragment build(FragmentTransaction fragmentTransaction) {
//            mCourseFeedbackDialogFragment.show(fragmentTransaction, mTag);
            fragmentTransaction.add(mCourseFeedbackDialogFragment, mTag);
            fragmentTransaction.commitAllowingStateLoss();
            return mCourseFeedbackDialogFragment;
        }

    }
}
